import plugin from '../../../lib/plugins/plugin.js'
import fs from 'fs'
import co from '../../../lib/common/common.js'
import { createRequire } from 'module'
import { common } from '../model/index.js'
import YAML from 'yaml'
const require = createRequire(import.meta.url)
const { exec, execSync } = require('child_process')
const plugin_path = process.cwd() + '/plugins/'
const example_path = process.cwd() + '/plugins/example/'
const cp_path = plugin_path + 'xiaoyue-plugin/resources/close/'
export class txcj extends plugin {
  constructor () {
    super({
      /** 功能名称 */
      name: '查询插件',
      /** 功能描述 */
      dsc: '查询插件',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 5000,
      rule: [
        {
          reg: '^#?(小月)?(查询插件|(确认)?卸载插件(\\d+))$',
          fnc: 'cx',
        },
        {
          reg: '^#?(小月)?(停用插件|启用插件)(\\d+)$',
          fnc: 'kg',
        },
        {
          reg: '^#?(小月)?停用插件列表$',
          fnc: 'close',
        }
      ]
    })
  }
 
  async cx(e){
    if (!e.isMaster) return false
    if (!fs.existsSync(cp_path)) fs.mkdirSync(cp_path)
    let plugin = fs.readdirSync(plugin_path)
    plugin = plugin.toString().replace(/.gitignore,|example,|genshin,|system,|other,/g, '').split(',')
    let example = fs.readdirSync(example_path)
    example = example.filter(file => file.endsWith(".js"))
    let msg = [`插件：${plugin.length} plugin | ${example.length} js\n指令：\n[卸载插件(序列号)][停用插件(序列号)]`]
    for (let i = 0; i < plugin.length; i++) {
      msg.push(`${i+1}.${plugin[i]}`)
    }
    msg.push('=======================\n以下为安装的js插件')
    for (let i = 0; i < example.length; i++) {
      msg.push(`${plugin.length +1 + i}.${example[i]}`)
    }
    if (/卸载插件/.test(e.msg)) {
      let emsg = e.msg.replace(/确认|卸载插件|#/g, '').trim()
      let fenhao = plugin.length + 1
      if (emsg < 1 || emsg > plugin.length + example.length) return e.reply('请检查序列号是否正确')
      if (emsg >= fenhao) emsg = Number(emsg) + 1
      let name = msg[emsg].replace(/^\d+./, '')
      if (/确认/.test(e.msg)) {
      
      if (fs.existsSync(plugin_path + name)) {
        try {
        await delDir(plugin_path + name)
        } catch(err) {
        let cm = `rm -rf ${plugin_path + name}`
        await this.execSync(cm)
        }
        e.reply(`卸载${name}成功，因为卸载的是plugin插件\n需重启才能生效，请自行重启云崽`)
      } else if (fs.existsSync(example_path + name)) {
        try {
        fs.unlinkSync(example_path + name)
        } catch (err) {
          let cm = `rm -rf ${example_path + name}`
          await this.execSync(cm)
        }
        e.reply(`卸载${name}成功`)
      }
  } else {
    e.reply(`是否确认卸载${name}，是请发送\n[#确认${e.msg.replace(/#/g, '')}]`)
  }
    return true
  }
   let reply = await e.reply(await co.makeForwardMsg(e,msg,'点击显示插件'))
   if (!reply) e.reply('风控了')
  }

  async kg(e) {
    if (!e.isMaster) return false
    if (!fs.existsSync(cp_path)) fs.mkdirSync(cp_path)
    let data = fs.readdirSync(cp_path)
    if (e.msg.includes('启用')) {
      let msg = e.msg.replace(/启用插件|#/g, '').trim()
      msg = Number(msg)
      if (msg < 1 || msg > data.length) return e.reply('请检查序列号是否正确')
      let name = data[msg-1]
      let res = await common.cp(true,name)
      await common.sleep(2000)
      if (!res) return e.reply(`启用插件[${name}]失败`)
      let js = name.includes('.js')
      let del = cp_path + name
      if (js) {
      fs.unlinkSync(del)
    } else {
      await delDir(del)
      await this.execSync(`rm -rf ${del}`)
    }
       e.reply(`启用插件[${name}]成功`)
       return true
    }
    let plugin = fs.readdirSync(plugin_path)
    plugin = plugin.toString().replace(/.gitignore,|example,|genshin,|system,|other,/g, '').split(',')
    let example = fs.readdirSync(example_path)
    example = example.filter(file => file.endsWith(".js"))
    let msg = [`插件：${plugin.length} plugin | ${example.length} js\n指令：[卸载(序列号)][停用插件(序列号)]`]
    for (let i = 0; i < plugin.length; i++) {
      msg.push(`${i+1}.${plugin[i]}`)
    }
    msg.push('=======================\n以下为停用的js插件')
    for (let i = 0; i < example.length; i++) {
      msg.push(`${plugin.length +1 + i}.${example[i]}`)
    }
    let emsg = e.msg.replace(/停用插件|启用插件|#/g, '').trim()
    let fenhao = plugin.length + 1
    if (emsg < 1 || emsg > plugin.length + example.length) return e.reply('请检查序列号是否正确')
    if (emsg >= fenhao) emsg = Number(emsg) + 1
    let name = msg[emsg].replace(/^\d+./, '')
    if (name.includes('xiaoyue-plugin')) return e.reply('想停用小月?醒醒吧你')
    if (data.includes(name)) return e.reply(`插件[${name}]已在停用列表中`)
    let res = await common.cp(false,name)
    await common.sleep(2000)
    if (!res) return e.reply(`停用插件[${name}]失败`)
    let js = name.includes('.js')
    let del
    if (js) {
      del = example_path + name
      fs.unlinkSync(del)
    } else {
      del = plugin_path + name
      await delDir(del)
      await this.execSync(`rm -rf ${del}`)
    }
    e.reply(`停用插件[${name}]成功，可发[停用插件列表]查看`)
  }

  async close(e) {
    if (!e.isMaster) return false
    if (!fs.existsSync(cp_path)) fs.mkdirSync(cp_path)
    let data = fs.readdirSync(cp_path)
    if (!data.length) return e.reply('暂无停用的插件')
    let msg = [`共停用了${data.length}个插件，指令[启用插件(序列号)]`]
    for (let i = 0; i < data.length; i++) {
        msg.push(`${i+1}.${data[i]}`)
    }
    common.getforwardMsg(e,msg,'停用插件列表',0,false,true)
  }

  async execSync (cmd) {
    return new Promise((resolve, reject) => {
      exec(cmd, { windowsHide: true }, (error, stdout, stderr) => {
        resolve({ error, stdout, stderr })
      })
    })
  }
}

async function delDir(dir) {
  let files = fs.readdirSync(dir)
  for (let v of files) {
      let newpath = dir + "/" + v
      let stats = fs.statSync(newpath)
      if (stats.isFile()) {
          fs.unlinkSync(newpath)
      } else {
          delDir(newpath)
      }
  }
  fs.rmdirSync(dir)
}
